package com.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.tool.StringTool;
import com.course.domain.pojo.CourseTag;
import com.course.domain.vo.TreeCourseTagsVo;
import com.course.mapper.CourseTagMapper;
import com.course.service.ICourseTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程标签表 服务实现类
 * </p>
 *
 * @author 小杰大人
 * @since 2025-09-26
 */
@Service
public class CourseTagServiceImpl extends ServiceImpl<CourseTagMapper, CourseTag> implements ICourseTagService {

    @Override
    public List<CourseTag> getCourseTags() {
        return list();
    }

    @Override
    public CourseTag getCourseTagById(Long courseTagId) {
        return this.getById(courseTagId);
    }

    @Override
    public List<CourseTag> getCourseTagsByCourseId(String tagIds) {
        List<Long> ids = StringTool.convertIdsToList(tagIds);
        if (ids == null){
            return null;
        }
        return this.listByIds(ids);
    }

    @Override
    public List<String> getCourseTagNamesByIds(String tagIds) {
        List<Long> ids = StringTool.convertIdsToList(tagIds);
        if (ids == null){
            return null;
        }
        return baseMapper.getCourseTagNamesByCourseId(ids);
    }

    @Override
    public List<TreeCourseTagsVo> getCourseTagsAsTree() {
        List<CourseTag> tags = baseMapper.getCourseTagsAsTree();
        Map<Long, TreeCourseTagsVo> parentMap = new HashMap<>();
        int i = 0;
        for (; i < tags.size(); i++) {
            CourseTag cur = tags.get(i);
            if (cur.getParentId() != null){
                break;
            }
            parentMap.put(tags.get(i).getId(), new TreeCourseTagsVo(cur.getId(), cur.getName(), new ArrayList<>()));
        }
        for (; i < tags.size(); i++) {
            CourseTag cur = tags.get(i);
            TreeCourseTagsVo par = parentMap.get(cur.getParentId());
            par.getChildren().add(new TreeCourseTagsVo(cur.getId(), cur.getName(), null));
        }
        return new ArrayList<>(parentMap.values());
    }



    @Override
    @Transactional
    public boolean deleteTagById(Long id) {
        Assert.notNull(id, "标签ID不能为空");
        return this.remove(new LambdaQueryWrapper<CourseTag>()
                .eq(CourseTag::getParentId, id)
                .or()
                .eq(CourseTag::getId, id)
        );
    }

}
